package com.lemon.utils;

import cn.hutool.core.io.FileUtil;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.googleapis.media.MediaHttpUploader;
import com.google.api.client.googleapis.media.MediaHttpUploaderProgressListener;
import com.google.api.client.http.InputStreamContent;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.ThumbnailSetResponse;
import com.google.api.services.youtube.model.Video;
import com.lemon.dto.MyVideo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.Arrays;

@Component
@Slf4j
public class YoutubeUtil {

    private static final String VIDEO_FILE_FORMAT = "video/*";

    public boolean upVideoToYoutube(YouTube youtube, MyVideo myVideo) {
        try {

            log.info("Uploading: " + myVideo.getUrlPath());

            InputStreamContent mediaContent = new InputStreamContent(VIDEO_FILE_FORMAT,
                    new BufferedInputStream(new FileInputStream(new File(myVideo.getUrlPath()))));
            mediaContent.setLength(myVideo.getVideoLen());

            YouTube.Videos.Insert videoInsert = youtube.videos()
                    .insert(Arrays.asList("snippet,statistics,status".split(",")), myVideo.getYoutubeVideo(), mediaContent);

            MediaHttpUploader uploader = videoInsert.getMediaHttpUploader();
            uploader.setDirectUploadEnabled(false);
            MediaHttpUploaderProgressListener progressListener = new MediaHttpUploaderProgressListener() {
                public void progressChanged(MediaHttpUploader uploader){
                    try {
                        switch (uploader.getUploadState()) {
                            case INITIATION_STARTED:
                                log.info("启动开始");
                                break;
                            case INITIATION_COMPLETE:
                                log.info("启动完成");
                                break;
                            case MEDIA_IN_PROGRESS:
                                log.info("上传进度: {} %", uploader.getProgress()*100);
                                break;
                            case MEDIA_COMPLETE:
                                log.info("上传完成!");
                                break;
                            case NOT_STARTED:
                                log.info("Upload Not Started!");
                                break;
                        }
                    } catch (Exception e) {
                        log.error("视频上传异常", e);
                    }
                }
            };

            uploader.setProgressListener(progressListener);

            Video returnedVideo = videoInsert.execute();

            log.info("\n================== Returned Video ==================\n");
            log.info("  - Id: " + returnedVideo.getId());
            log.info("  - Title: " + returnedVideo.getSnippet().getTitle());
            log.info("  - Tags: " + returnedVideo.getSnippet().getTags());
            log.info("  - Privacy Status: " + returnedVideo.getStatus().getPrivacyStatus());
            log.info("  - Video Count: " + returnedVideo.getStatistics().getViewCount());

            // 上传缩略图
            File mediaFile = new File(myVideo.getPicPath());
            InputStreamContent mediaPic =
                    new InputStreamContent("application/octet-stream",
                            new BufferedInputStream(new FileInputStream(mediaFile)));
            mediaPic.setLength(myVideo.getPicLen());

            YouTube.Thumbnails.Set set = youtube.thumbnails().set(returnedVideo.getId(), mediaPic);
            ThumbnailSetResponse execute = set.execute();
            System.out.println(execute.toPrettyString());

            return true;
        } catch (GoogleJsonResponseException e) {
            log.error("GoogleJsonResponseException code: " + e.getDetails().getCode() + " : "
                    + e.getDetails().getMessage());
        } catch (IOException e) {
            log.error("IOException.", e);
        } catch (Throwable t) {
            log.error("Throwable.", t);
        }
        return false;
    }
}
